package service

import (
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/global"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"time"
)

type AfterSaleSrv struct{}

func (a AfterSaleSrv) Statistics(req request.Statistics) response.Resp {
	statistics := map[string]interface{}{
		"pre":  0,
		"next": 0,
	}
	filter := bson.D{bson.E{Key: "shopId", Value: req.ShopId}}

	// 上月
	now := time.Now()
	today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
	lastFifteenDate := time.Date(now.Year(), now.Month(), now.Day()-15, 0, 0, 0, 0, time.Local)
	lastThirtyDate := time.Date(now.Year(), now.Month(), now.Day()-30, 0, 0, 0, 0, time.Local)

	preFilter := append(filter, bson.E{
		Key: "createdAt",
		Value: bson.M{
			"$gte": lastThirtyDate.Unix() * 1000,
			"$lte": today.Unix() * 1000,
		},
	})
	nextFilter := append(filter, bson.E{
		Key: "createdAt",
		Value: bson.M{
			"$gte": lastFifteenDate.Unix() * 1000,
			"$lte": today.Unix() * 1000,
		},
	})
	pTotal, err := global.MongoDB.Collection("refund_order").CountDocuments(context.TODO(), preFilter)
	if err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}

	nTotal, err := global.MongoDB.Collection("refund_order").CountDocuments(context.TODO(), nextFilter)
	if err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}

	statistics["pre"] = pTotal
	statistics["next"] = nTotal
	return response.OK.WithData(statistics)
}
